package com.neeraj.SharingArtifacts;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class UseCamcorder extends Activity implements OnTouchListener, LocationListener, OnCancelListener {
	
	private static final String DEBUG_TAG = "Use Camcorder";
	
	final static int REQUEST_VIDEO_CAPTURED = 1;
	
	private static final int MEDIA_TYPE_VIDEO = 3;
	private static final int WAIT_DIALOG_ID = 1;
	Uri uriVideo = null;
	File copyFile = null;
	private LocationManager locationManager;
	private Location location;
	private String bestProvider;

	RelativeLayout rel;
	DatabaseHelper dbHelper;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.use_camcorder);

        rel = (RelativeLayout) findViewById(R.id.relativeLayoutTap);
        rel.setOnTouchListener(this);    
           
		if (!Geocoder.isPresent()){
        	Toast.makeText(getBaseContext(),
        	"Sorry! Geocoder service not Present.",
        	Toast.LENGTH_LONG).show();
        }
        showDialog(WAIT_DIALOG_ID);
 		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);     		

   		Criteria criteria = new Criteria();
   		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
  		criteria.setAccuracy(Criteria.ACCURACY_FINE);
   		bestProvider = locationManager.getBestProvider(criteria, false);

   		location = locationManager.getLastKnownLocation(bestProvider); 
    }
    
	@Override
	public void onStart()
	{
		try {
			super.onStart();
			dbHelper=new DatabaseHelper(this);
			dbHelper.insertTypeData();
		} catch(Exception ex) {			
			CatchError(ex.toString());
		}
	}

    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			if(requestCode == REQUEST_VIDEO_CAPTURED){
				uriVideo = data.getData();
//				uriVideo.
				Log.d(DEBUG_TAG, "This is the path where file is stored:"+uriVideo.getPath());	
				Log.d(DEBUG_TAG, "Absolute path:"+ getRealPathFromURI(uriVideo));
				copyFile = getOutputMediaFile(MEDIA_TYPE_VIDEO); // create a file to save the video
				File imageFile = new File(getRealPathFromURI(uriVideo));
				try {
					copyDirectory(imageFile, copyFile);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Toast.makeText(this,"Video saved to: " + copyFile.getPath(), 
						Toast.LENGTH_LONG)
						.show();
				Log.d(DEBUG_TAG, "in on create" + location.getLatitude() + ", " + location.getLongitude());
		   		saveAttributes();
			}
		}else if(resultCode == RESULT_CANCELED){
			uriVideo = null;
			Toast.makeText(this, "Cancelled!", 
					Toast.LENGTH_LONG)
					.show();
		}
	}
	
	@Override
    protected void onResume() {
		super.onResume();		
		locationManager.requestLocationUpdates(bestProvider, 1000, 1, this);
	}

	/** Stop the updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
		
		//Specify target file
		String MyVideoFilePath = "/sdcard/test/myvideo.mp4";
		File imageFile = new File(MyVideoFilePath);
		Uri imageFileUri = Uri.fromFile(imageFile);		
		
		Log.d(DEBUG_TAG, "imageFileUri" + imageFileUri.toString());
		System.out.println("imageFileUri" + imageFileUri.toString());
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
		//---
		
		startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
		return false;
	}
	
	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type){
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_DCIM), "SharingArtifacts/video");

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d(DEBUG_TAG, "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
	    File mediaFile;
	    if(type == MEDIA_TYPE_VIDEO) {
	    	Log.d(DEBUG_TAG, "mediaStorageDir:" + mediaStorageDir.toString());
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "VID_"+ timeStamp + ".mp4");
	        Log.d(DEBUG_TAG, "mediaFile:" + mediaFile.toString());
	    } 
	    else {
	        return null;
	    }
	    Log.d(DEBUG_TAG, "mediaFile Out:" + mediaFile.toString());
	    return mediaFile;
	}
	
	public void copyDirectory(File sourceLocation , File targetLocation)
		    throws IOException {
		        
		if (sourceLocation.isDirectory()) {
			if (!targetLocation.exists()) {
		                targetLocation.mkdir();
		    }
		            
		    String[] children = sourceLocation.list();
		    for (int i=0; i<children.length; i++) {		    
		    	copyDirectory(new File(sourceLocation, children[i]),
		                        new File(targetLocation, children[i]));
		    	new File(sourceLocation, children[i]).delete();
		    }
		} else {
			InputStream in = new FileInputStream(sourceLocation);
		    OutputStream out = new FileOutputStream(targetLocation);
		            
		    // Copy the bits from input stream to output stream
		    byte[] buf = new byte[1024];
		    int len;
		    while ((len = in.read(buf)) > 0) {
		                out.write(buf, 0, len);
		    }
		    in.close();
		    out.close();
		    sourceLocation.delete();
		}
	}
	
	public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

	private String getDate() {
		String date;
		final Calendar c = Calendar.getInstance();
		int myYear = c.get(Calendar.YEAR);
		int myMonth = c.get(Calendar.MONTH);
		String monthStr=null;
//		String dayStr = null;
		if(myMonth < 10 )
			monthStr = "0"+String.valueOf(myMonth+1);
		int myDay = c.get(Calendar.DAY_OF_MONTH);
//		if(myDay < 10)
//			dayStr = "0"+String.valueOf(myDay);
		
		date = String.valueOf(myYear) + "-"
			       + monthStr + "-" + String.valueOf(myDay);
		
		return date;
	}
	
	void CatchError(String Exception) {	    	
    	Dialog diag=new Dialog(this);
    	diag.setTitle("Error!!!");
    	TextView txt=new TextView(this);
    	txt.setText(Exception);
    	diag.setContentView(txt);
    	diag.show();
    }
	
	void saveAttributes() {
		Log.d(DEBUG_TAG, "in save attributes!!!");
		Bundle b = new Bundle();
		b.putDouble("latitude", getLatitude());
		b.putDouble("longitude", getLongitude());
		b.putDouble("altitude", getAltitude());
		b.putLong("utc_time", getTime());
		b.putString("date", getDate());
		b.putString("artifactType", "video");
		b.putString("content", copyFile.getPath());
		b.putString("content_file_name", copyFile.getName());
		b.putInt("isUpload", 0);
		
		dbHelper.insertData(b,MEDIA_TYPE_VIDEO);
	}
	
	protected Dialog onCreateDialog(int id) {
   	 // TODO Auto-generated method stub
   	 Dialog alertDialog = null;;
   	    switch(id) {
   	    case WAIT_DIALOG_ID:
   			alertDialog = new ProgressDialog(this);
   			((ProgressDialog)alertDialog).setMessage("Waiting for GPS location...");
   			alertDialog.setCancelable(true);
   			alertDialog.setOnCancelListener(this);
   			break;
   	    }
   	    return alertDialog;
   }
   
	@Override
	public void onCancel(DialogInterface dialog) {
		// TODO Auto-generated method stub
		removeDialog(WAIT_DIALOG_ID);
	}

	@Override
	public void onLocationChanged(Location loc) {
		// TODO Auto-generated method stub
		location = loc;
	    location.getLatitude();
	    location.getLongitude();
//	    dismissDialog(WAIT_DIALOG_ID);
	    removeDialog(WAIT_DIALOG_ID);
	    String Text = "My current location is:" + "Latitude = " + 
	    		location.getLatitude() + ",Longitude = " + location.getLongitude();
	    Toast.makeText( this, Text, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText( this, "Gps Disabled", Toast.LENGTH_SHORT ).show();
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText( this, "Gps Enabled", Toast.LENGTH_SHORT ).show();
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub		
	}
	
	double getLatitude() {
		return location.getLatitude();
	}
	
	double getLongitude() {
		return location.getLongitude();
	}
	
	double getAltitude() {
		return location.getAltitude();
	}
	
	long getTime() {
		return location.getTime();
	}
}
